package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.PeachblossomApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Peachblossom;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PeachblossomVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author : RYR
 * @description :  桃花传音业务层
 * @createTime : 2022/1/2 14:48
 */
@Service
public class PeachblossomService {

    @DubboReference
    private PeachblossomApi peachblossomApi;
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 接收语音
     * @return
     */
    public PeachblossomVo receive() {
        //  通过当前id，获取用户信息
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        //  1. 在MongoDB数据库随机查询一条语音数据
        Peachblossom peachblossom = peachblossomApi.findRandomUrl(UserHolder.getUserId(),userInfo.getGender());
        if(peachblossom == null){
            return new PeachblossomVo();
        }
        //  获取出发送语音消息的人的id
        Long sendUserId = peachblossom.getUserId();

        //  查询redis，没有保存，有判断次数。并存入redis，记录数量和时间
        String value = redisTemplate.opsForValue().get(Constants.PEACHBLOSSOM_KEY+UserHolder.getUserId());
        if(value == null){                                                  //  TODO   测试写的60秒，查看到时间能否删除    正式写成一天
            redisTemplate.opsForValue().set(Constants.PEACHBLOSSOM_KEY+UserHolder.getUserId(), "1",60, TimeUnit.SECONDS);
        }else{
            // redis中有数据 ，将value的值，增加长度
            redisTemplate.opsForValue().set(Constants.PEACHBLOSSOM_KEY+UserHolder.getUserId(),value+1,
                    //   getExpire  方法可以的到上次设置的时间数据,不修改第一次设置的时间
                    (redisTemplate.getExpire(Constants.PEACHBLOSSOM_KEY+UserHolder.getUserId())), TimeUnit.SECONDS);
//                    60, TimeUnit.SECONDS);
            peachblossom.setRemainingTimes(10-(value.length()));
            if(value.length()==10){
                throw new BusinessException(ErrorResult.countError());
            }
        }
        //  接收完这个语音，把这条语音删除
        UserInfo info = userInfoApi.findById(sendUserId);
//        peachblossomApi.delete(peachblossom);      //  TODO， 测试数据，先不调用删除
        //  转换成vo对象
        PeachblossomVo init = PeachblossomVo.init(info, peachblossom);
        return init;
    }

    /**
     * 发送语音的功能
     * @param soundFile 语音的内容
     */
    public void send(MultipartFile soundFile) throws IOException {
        //  当前用户的id
        Long userId = UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        //  将语音存入到oss阿里云，得到url地址值
        String soundUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
        //  创建对象，设置属性
        Peachblossom peachblossom = new Peachblossom();
        peachblossom.setUserId(userId);
        peachblossom.setSoundUrl(soundUrl);
        peachblossom.setGender(userInfo.getGender());
        peachblossom.setCreated(System.currentTimeMillis());
        //  调用mongon  进行保存数据内容
        Boolean aBoolean = peachblossomApi.saveUrl(peachblossom);
        if(!aBoolean){
            throw new BusinessException(ErrorResult.voiceError());
        }

    }



}
